local skynet = require "skynet"
local manager = require 'skynet.manager'

local CMD = {}
local Players = {}

function CMD.CreateAvatar(loginAgent, playerId)
    --同一个playerId创建avatar，顶号
    if Players[playerId] then
        skynet.call(Players[playerId], 'lua', 'kick')
    end
    local avatar = skynet.newservice("avatar/avatar")
    local conv = skynet.call(avatar, "lua", "Start", loginAgent, playerId)
    Players[playerId] = avatar
    return avatar, conv
end

function CMD.Reconnect(loginAgent, playerId, conv)
    local avatar = Players[playerId]
    --进程找不到(可能已经被销毁了)
    if avatar == nil then return false end
    --之前的loginAgent的进程还没检测到断开新的Reconnect消息就来了，那就要处理之前loginAvatar的进程
    local ok = skynet.call(avatar, 'lua', 'OnReconnect', loginAgent, playerId, conv)
    return ok, avatar
end

function CMD.RemoveAvatar(playerId)
    Players[playerId] = nil
end

skynet.start(function()
    skynet.dispatch("lua", function(_, _, cmd,  ...)
        local f = assert(CMD[cmd])
        skynet.ret(skynet.pack(f(cmd, ...)))
    end)
    manager.register('avatarManager')
end)

